package com.chu.cloud.task;

import com.chu.cloud.redis.RedisLockUtil;
import com.chu.cloud.service.CouponService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/5/3 15:41
 * @Description: 店铺优惠券过了领取结束时间将状态置为已过期
 */
@Component
@Slf4j
public class ExpiredCouponCleanerTask {

    private static final String key = "clean_expired_coupon_event";
    private static final int TIMEOUT = 3 * 1000;

    private final CouponService couponService;
    private final RedisLockUtil redisLockUtil;

    public ExpiredCouponCleanerTask(CouponService couponService, RedisLockUtil redisLockUtil) {
        this.couponService = couponService;
        this.redisLockUtil = redisLockUtil;
    }

    @Scheduled(cron = "0 0 23 * * ?")
    public void cleanExpiredCoupon() {
        long time = System.currentTimeMillis() + TIMEOUT;
        if (!redisLockUtil.lock(key,String.valueOf(time))){
            return;
        }
        log.info("当前执行清理过期优惠券时间:{}", DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        couponService.cleanExpiredCoupon();
        redisLockUtil.unlock(key,String.valueOf(time));
    }

}
